//
// Created by 15271 on 2023/5/26.
//
#include <thread>
#include "ResetServer.h"
#include "ConfigApi.h"
#include "HttpCmdProcess.h"
#include "Protocol/ProtocolApi.h"

using namespace Protocol;

using namespace ConfigApi;

ResetServer *ResetServer::sm_resetServer = nullptr;
mutex ResetServer::sm_instanceLock;

void ResetServerInit(){
    ResetServer::instance();
}
ResetServer *ResetServer::instance(){
    if(sm_resetServer == nullptr){
        lock_guard<mutex> instanceLock(sm_instanceLock);
        sm_resetServer = new ResetServer();
    }
    return sm_resetServer;
}

ResetServer::ResetServer(){
    RegistRPC();
}

void ResetServer::RegistRPC(){
    RPCMethodMap method_map;
	method_map.emplace("InitReset", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return InitReset(request, inMap, response, outMap);
	}));
	
	IProtocolInterface::GetInstance()->RegistProtocol("Reset", method_map);
}


bool ResetServer::InitReset(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, Json::Value &response, Fdt::BufferMap::Ptr &outMap){
    return resetConfig() && WlanOpt();
}
bool ResetServer::resetConfig(){
    //重新设置设备名称，密码，WIFI信息
    Json::Value nameTable;
    nameTable["Name"] = "NearHub_Rooms";
    if(!IConfigInterface::GetInstance()->Set("DevName", nameTable, ConfigOptions::ConfigOptionSaveAll)){
		return false;
    }
    Json::Value devPasswdTable;
    devPasswdTable["Keys"] = "";
    devPasswdTable["Enable"] = false;	
	if(!IConfigInterface::GetInstance()->Set("DevPasswd", nameTable, ConfigOptions::ConfigOptionSaveAll)){
		return false;
	}
    Json::Value wifiTable;
    wifiTable["SSID"] = "";
    wifiTable["key"] = "";
    wifiTable["Connected"] = false;    
	if(!IConfigInterface::GetInstance()->Set("Wifi", nameTable, ConfigOptions::ConfigOptionSaveAll)){
		return false;
	}
    return true;
}
bool ResetServer::WlanOpt(){
	//单独开一个线程执行耗时的WiFi断开连接和AP重开的操作
	//Wifi断开连接	
	//AP重新设置
	Json::Value apTable;
	apTable["Password"] = "";
	apTable["FreqBand"] = "";
	apTable["Retransmit"] = 1;
	Media::HttpCmdProcess::instance()->openApService(apTable);

	return true;
}
